package com.chhuang.tutool.ui.fragment

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.chhuang.tutool.R
import com.chhuang.tutool.adapter.MessageListAdapter
import com.chhuang.tutool.databinding.FragmentTcpServerBinding
import com.chhuang.tutool.modle.MessageBean
import com.chhuang.tutool.socket.NettyUDP
import com.gnetek.tool.base.BaseFragment
import com.gnetek.tool.socket.NettyClient
import com.swallowsonny.convertextlibrary.hex2ByteArray
import com.swallowsonny.convertextlibrary.toHexString
import com.xuexiang.xui.utils.WidgetUtils
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread

class UDPFragment(private val ip:String, private val port:Int, private val loaclPort: Int) : BaseFragment() {
    companion object {
        private const val TAG = "UDPFragment"
    }

    private lateinit var binding: FragmentTcpServerBinding

    //列表适配器
    private val messageListAdapter = MessageListAdapter(mutableListOf())

    private var nettyUDP: NettyUDP? = null

    override fun bindView(inflater: LayoutInflater, container: ViewGroup?): View {
        binding = FragmentTcpServerBinding.inflate(inflater, container, false)
        val view: View = binding.root
        return view
    }

    override fun initView() {
        WidgetUtils.initRecyclerView(binding.messageRecyclerView)
        binding.messageRecyclerView.adapter = messageListAdapter
    }

    override fun initListener() {
        binding.sendButton.setOnClickListener {
            val content = binding.contentEditText.text
            if(content.isNotBlank()) {
                val message = content.toString()
                Log.e(TAG, "initListener: ${message}")
                val data = if(binding.hexSwitchButton.isChecked){
                    message.hex2ByteArray()
                }else {
//                    message.ascii2ByteArray()
                    message.toByteArray(Charsets.UTF_8)
//                    message.toByteArray(Charset.forName("GBK"))
                }
                nettyUDP?.let {
                    it.doBroadcast(data)
                    val local = it.getLocalSocketAddress()
                    val messageBean = if(local!=null){
                        MessageBean(if(local.address.hostAddress==null)"local sender" else local.address.hostAddress,
                            local.port,
                            message)
                    }else {
                        MessageBean("local sender", -1, message)
                    }
                    messageListAdapter.loadOne(messageBean)
                    xToasts(R.string.send_success, 1)
                    binding.contentEditText.text = null
                }
            }
        }
    }

    override fun initData() {
        doAsync {
            NettyUDP(ip, port, loaclPort, {
                nettyUDP = it
                uiThread {
                    xToasts(R.string.connect_success, 1)
                }
            },{//连接失败
                uiThread {
                    xToasts(R.string.connect_failed,0)
                }
            },{it, ip, port->
                val datas = it
                uiThread {
                    val message = if(binding.hexSwitchButton.isChecked){
                        datas.toHexString()
                    }else {
//                        datas.readStringBE(0, datas.size,"ascii")
                        String(datas, Charsets.UTF_8)
//                        String(datas, Charset.forName("GBK"))
                    }
                    Log.e(TAG, "initData: ${message}" )
                    val messageBean = MessageBean(ip, port, message,false)
                    messageListAdapter.loadOne(messageBean)
                }
            })
        }
    }

    override fun onDestroy() {
        nettyUDP?.destroy()
        super.onDestroy()
    }
}